package com.dmz.task.service;

import cn.hutool.core.io.FileUtil;
import com.dmz.common.utils.secure.GMUtil;
import com.dmz.task.bean.entity.TDocInfo;
import com.dmz.task.model.ApiResult;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lee
 */
@Service
@Slf4j
public class OtherService {

    @Value("${zynj.sftp.id}")
    private long zynjSftpId;
    @Value("${glfwzx.ftp.id}")
    private long fwzxdzftpId;

    @Value("${sm4.key}")
    private String key;

    @Value("${sm4.iv}")
    private String iv;

    @Resource
    private DocInfoService docInfoService;

    public ApiResult<String> zynjSftp(String date) throws Exception {

        TDocInfo doc = docInfoService.select(zynjSftpId);

        String str = doc.getSrcPath();
        String time = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        if (date != null && !date.isEmpty()) {
            Calendar cal = new GregorianCalendar();
            cal.setTime(new Date());
            cal.add(5, -1);
            time = sdf.format(cal.getTime());
        } else {
            time = date;
        }
        str = str + File.separator + doc.getFileName().replace("{date}", time);

        log.info(str);
        //swsftp_104
        //31ZDymQs
        String username = GMUtil.db(key, iv, doc.getTgtUsername());
        String password = GMUtil.db(key, iv, doc.getTgtPassword());
        String ip = doc.getTgtHost();
        int port = doc.getTgtPort();
        boolean flag = connectUpload(username, password, ip, port, doc.getTgtPath(), str);
        if (flag) {
            System.out.println("upload:ok");
            return ApiResult.success("upload:ok");
        } else {
            System.out.println("upload:no");
            return ApiResult.fail("upload:no");
        }
    }

    public boolean connectUpload(String user, String pass, String ip, int port, String uploadFile, String fileName) {
        boolean result = true;
        ChannelSftp sftp = null;
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();

        try {
            session = jsch.getSession(user, ip, port);
            session.setPassword(pass);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect(30000);
            channel = session.openChannel("sftp");
            channel.connect(1000);
            sftp = (ChannelSftp) channel;
            System.out.println(" connect:OK！");
        } catch (Exception var19) {
            log.error(var19.getMessage(), var19);
            result = false;
        }

        if (result) {
            try {
                File srcFile = FileUtil.newFile(fileName);
                FileInputStream filein = new FileInputStream(srcFile);
                sftp.cd(uploadFile);
                System.out.println(srcFile.getName());
                sftp.put(filein, srcFile.getName());
                System.out.println("upload:ok");
            } catch (Exception var17) {
                log.error(var17.getMessage(), var17);
            } finally {
                session.disconnect();
                channel.disconnect();
                sftp.disconnect();
            }
        }
        return result;
    }


    public ApiResult<String> fwzxdzftp() throws Exception {

        TDocInfo doc = docInfoService.select(fwzxdzftpId);


        String fwzxuser = GMUtil.db(key, iv, doc.getTgtUsername());
        String fwzxpass = GMUtil.db(key, iv, doc.getTgtPassword());
        String fwzxip = doc.getTgtHost();
        int port = doc.getTgtPort();
        String saveFile = doc.getSrcPath();
        String downPath = doc.getTgtPath();
        List<File> files = getFields(saveFile);
        for (File f : files) {
            System.out.println(f.getName());
            boolean flag = priKeyUpload(port, fwzxuser, fwzxip, fwzxpass, saveFile, f.getName(), downPath);
            if (flag) {
                f.delete();
            }
        }
        return ApiResult.success("upload:ok");
    }

    private List<File> getFields(String srcpath) throws IOException {
        File root = FileUtil.newFile(srcpath);
        List files = new ArrayList();
        if (!root.isDirectory()) {
            files.add(root);
        } else {
            File[] suFiles = root.listFiles();
            File[] var7 = suFiles;
            int var6 = suFiles.length;

            for(int var5 = 0; var5 < var6; ++var5) {
                File f = var7[var5];
                files.addAll(getFields(f.getAbsolutePath()));
            }
        }

        return files;
    }

    public static boolean priKeyUpload(int port, String FTP_USERNAME, String FTP_IP, String password, String saveFile, String fileName, String downloadFile) {
        boolean result1 = true;
        ChannelSftp sftp = null;
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();

        Exception e;
        try {
            session = jsch.getSession(FTP_USERNAME, FTP_IP, port);
            session.setPassword(password);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect(300000);
            channel = session.openChannel("sftp");
            channel.connect(1000);
            sftp = (ChannelSftp)channel;
            System.out.println("通道建立成功");
        } catch (Exception var20) {
            log.error("SFTP连接失败", var20);
            result1 = false;
        }

        if (result1) {
            try {
                File srcFile = FileUtil.newFile(saveFile + fileName);
                FileInputStream filein = new FileInputStream(srcFile);
                sftp.cd(downloadFile);
                System.out.println(srcFile.getName());
                log.info("upload:ok" + new Date());
                sftp.put(filein, srcFile.getName());
                System.out.println("upload:ok");
            } catch (Exception var18) {
                log.error("SFTP上传失败" , var18);
                result1 = false;
            } finally {
                session.disconnect();
                channel.disconnect();
                sftp.disconnect();
            }
        }

        return result1;
    }


}
